<?php

namespace app\exam\controller;

use app\common\model\Company;
use app\common\model\Qbank;
use think\Controller;
use think\Request;
use think\Session;
use Faker\Factory;
use app\common\model\User as UserModel;

/**处理非认证用户的操作行为
 * Class Userwithoutauth
 * @package app\exam\controller
 */
class Userwithoutauth extends Controller
{
    /*
     * 注册页面，只提供get方法，根据不同用户选项判断是企业还是个人
     */
    /**
     * @return \think\response\View
     */
    public function signin()
    {
        if (Request::instance()->isPost()) {

        }
        if (Request::instance()->isGet()) {
//            foreach ($dbtest as $test){
//                echo $test->content;
//            }
            if (Session::get('user')) {
                return redirect('/exam/personalcenter');
            } else {
                return view('/sign-in/sign-in');
            }
        }
    }

    /**
     *个人注册函数
     */
    public function signin_user()
    {
        $data = Request::instance()->post();

        $validate = new \app\common\validate\User();
        if (!$validate->scene('sign-up')->check($data)) {
            $this->error($validate->getError());
        }
//        判断是否为测试模式，影响身份证接口的调用
        if (config('test_mode')) {
            $code = 0;
            $checkID['sex'] = '男';
        } else {
            $checkID = validateIDnumber($data['id-number'], $data['real-name']);
            $checkID = json_decode($checkID);
            $code = $checkID->resp->code;
            if (Session::get('SMS')['time'] >= time() && Session::get('SMS')['captcha'] == $data['captcha']) {
            } else {
                $this->error('验证码错误');
            }
        }

        $checkCompany = Company::where('name', $data['company_name'])->where('credit_number', $data['company_number'])->find();
        if (!$checkCompany) {
            $this->error('请先完成企业注册');
        } else {
            if ($code == '0') {
                $user = new UserModel();
                $user->name = $data['username'];
                $user->real_name = $data['real-name'];
                $user->idcard = $data['id-number'];
                $user->password = md5($data['password']);
                $user->company_name = $data['company_name'];
                $user->sex = $checkID['sex'];

                $data = \request()->file('user_company');
                $info = $data->move(ROOT_PATH . 'public' . DS . 'uploads' . DS . 'user_company');
                $save = $user->save(['company_image' => $info->getSaveName()]);

                if ($save) {
                    $us = array('user_id' => $user->id);
                    Session::set('user', $us);
                    $this->success('注册用户成功', '/personalcenter');
                } else {
                    $this->error('注册用户失败');
                }
            } elseif ($code == '5' || $code == '14') {
                $this->error('身份证信息不正确');
            } else {
                $this->error('系统接口错误');
            }
        }
    }


    /**
     *企业注册函数
     */
    public function signin_company()
    {
        $data = Request::instance()->post();
//dump($data);
        $validate = new \app\common\validate\Company();
        if (!$validate->scene('sign-up')->check($data)) {
            $this->error($validate->getError());
        }
        if (count(Company::where('credit_number', $data['company_number'])->select())) {
            $this->error('企业已存在');
        }
        if (config('test_mode')) {
            $checkCompany = 'success';
        } else {
            $checkCompany = validateCompany($data['company_name'], $data['company_number'], $data['company_address']);
        }
        if ($checkCompany == 'success') {
            $company = new Company();
            $company->name = $data['company_name'];
            $company->address = $data['company_address'];
            $company->credit_number = $data['company_number'];
            $data = \request()->file('avatar');

            $save = $company->save();

            $info = $data->move(ROOT_PATH . 'public' . DS . 'uploads' . DS . 'company' . DS . $company->id);
            $company->company_image = $info->getSaveName();
            $save = $company->save();
            if ($save) {
                $this->success('注册企业成功');
            } else {
                $this->error('注册企业失败');
            }
        } else {
            $this->error('企业信息不正确');
        }
        return;

    }

    /**个人登录页面
     * @return \think\response\View
     */
    public function login()
    {
        if (Request::instance()->isGet()) {
            if (Session::get('user')['user_id']) {
                return redirect('/exam/personalcenter');
            } else {
                return view('sign-in/login');
            }
        }
        if (Request::instance()->isPost()) {
            if (Session::get('user', 'think')['user_id']) {
                return redirect('/exam/personalcenter');
            } else {
                Session::clear();
                $data = Request::instance()->post();
                $username = $data['login-username'];
                $password = md5($data['login-password']);
                $user = UserModel::where('name', $username)->where('password', $password)->find();
                if ($user) {
                    $session_user['user_id'] = $user->id;
                    $session_user['name'] = $user->name;
                    Session::set('user', $session_user);
                    $user->save(['last_login' => date('Y-m-d H:i:s', time())]);
                    $this->success('登录成功', view('PersonalCenter/user'));
                } else {
                    $this->error('登录失败');
                }
            }
        }
    }


    public function test()
    {
        $aa = validateCompany("今日幸福移动网络科技有限公司", '91120116300646102M', '天津滨海高新区华苑产业区工华道壹号D座2门6012');
//$bb=json_decode($aa);
        dump($aa);
//        echo $phone;
//        }
//        echo 'over';
    }

    /**根据前台提供的手机号，检索数据库之后发送验证码
     * @return string
     */
    public function sendSMS()
    {
        $phone_number = Request::instance()->post();
        $phone_number = $phone_number['phone_number'];
//        $user = \app\common\model\User::where('phone_number', $phone_number);
//        if ($user) {
//        dump($phone_number);
        $captcha = rand(1000, 9999);
        $result = json_decode(urldecode(SMS($phone_number, $captcha)));
//            $SMS['uid'] = $user->id;
        $SMS['captcha'] = $captcha;
        $SMS['time'] = time() + 60;
        Session::set('SMS', $SMS);

        if (!empty($result->errorMsg)) {
            return '请联系管理员.错误信息：' . $result->errorMsg;
        } else {

            return '验证码发送成功';
        }
//        } else {
//            return '用户不存在';
//        }
    }

    /**
     *检查收到的验证码与session中的数据是否相同
     */
    public
    function checkSMS()
    {
        $checkInfo = Request::instance()->post();
        $SMS = Session::get('SMS', 'think');
        if (!$checkInfo['captcha']) {
            if ($checkInfo['captcha'] == $SMS['captcha']) {
                $user = \app\common\model\User::where('uid', $SMS['uid']);
                $user->password = md5($SMS['password']);
                $user->save();
                $this->success('修改成功');
            } else {
                $this->error('验证码错误');
            }
        }
    }

    public function faker()
    {
        $faker = Factory::create();
        $abc = 'ABCDEFG';
        for ($i = 0; $i < 500; $i++) {
            $question = new Qbank();
            $type = rand(1, 5);
            $qbank = rand(1, 6);

            $question->qbank = $qbank;
            $question->content = $faker->sentence;
            $question->qtype=$type;
            $qans=array();
            switch ($type) {
                case 1:
                    $qnum = rand(3, 6);
                    for ($i = 0; $i < $qnum; $i++) {
                        $qans[$abc[$i]] = $faker->sentence;
                    }
                    $qas = array_rand($qans, 1);
                    $qa = $qas;
                    $qans = json_encode($qans);

                    break;
                case 2:
                    $qnum = rand(3, 6);
                    for ($i = 0; $i < $qnum; $i++) {
                        $qans[$abc[$i]] = $faker->sentence;
                    }
                    $qas = array_rand($qans, rand(2, $qnum));
                    $qa = '';
                    foreach ($qas as $q) {
                        $qa .= $q;
                    }
                    $qans = json_encode($qans);

                    break;
                case 3:
                    $qnum = '2';
                    $qans['A']='正确';
                    $qans['B']='错误';
                    $qa=rand(0,1);
                    $qa=$abc[$qa];
                    $qans=json_encode($qans);
                    break;
                case 4:
                    $qnum = rand(1, 6);
                    $qa='';
                    for($i=0;$i<$qnum;$i++){
                        $qa.=$faker->word.',';
                    }
                    $qa=substr($qa,0,strlen($qa)-1);
                    break;
                case 5:
                    $qnum = null;
                    $qa='';
                    break;
            }

            $question->qnum = $qnum;
            $question->qans=$qans;
            $question->qa=$qa;
            $question->save();
            echo $i;
        }
    }


}
